<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket调试工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        button {
            background-color: #007bff;
            color: white;
            cursor: pointer;
            margin-right: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .log {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 15px;
            height: 400px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
            white-space: pre-wrap;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            font-weight: bold;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .status.connecting {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        .api-section {
            margin-top: 20px;
            padding: 15px;
            background-color: #e9ecef;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>WebSocket调试工具</h1>
        
        <div class="form-group">
            <label for="userId">用户ID:</label>
            <input type="text" id="userId" value="1">
        </div>
        
        <div class="form-group">
            <label for="userName">用户名:</label>
            <input type="text" id="userName" value="测试用户">
        </div>
        
        <div class="form-group">
            <label for="roomId">房间ID:</label>
            <input type="text" id="roomId" value="test-room">
        </div>
        
        <div class="form-group">
            <button id="connectBtn" onclick="connect()">连接WebSocket</button>
            <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
            <button onclick="clearLog()">清空日志</button>
        </div>
        
        <div id="status" class="status disconnected">未连接</div>
        
        <div class="form-group">
            <label for="messageInput">发送消息:</label>
            <input type="text" id="messageInput" placeholder="输入消息内容" style="width: 60%;">
            <button onclick="sendMessage()">发送</button>
        </div>
        
        <div class="api-section">
            <h3>HTTP API测试</h3>
            <button onclick="testOnlineCount()">测试在线用户数</button>
            <button onclick="testUserStatus()">测试用户状态</button>
            <button onclick="testFriendsStatus()">测试好友状态</button>
            <button onclick="testAllOnlineUsers()">测试所有在线用户</button>
        </div>
        
        <div class="form-group">
            <label>消息日志:</label>
            <div id="log" class="log"></div>
        </div>
    </div>

    <script>
        let ws = null;
        let isConnected = false;

        function log(message) {
            const timestamp = new Date().toLocaleTimeString();
            const logElement = document.getElementById('log');
            logElement.textContent += `[${timestamp}] ${message}\n`;
            logElement.scrollTop = logElement.scrollHeight;
        }

        function updateStatus(status, className) {
            const statusElement = document.getElementById('status');
            statusElement.textContent = status;
            statusElement.className = `status ${className}`;
        }

        function connect() {
            const userId = document.getElementById('userId').value;
            const userName = document.getElementById('userName').value;
            const roomId = document.getElementById('roomId').value;
            
            if (!userId || !userName) {
                alert('请输入用户ID和用户名');
                return;
            }

            const url = `ws://localhost:9988/ws?userId=${encodeURIComponent(userId)}&userName=${encodeURIComponent(userName)}&roomId=${encodeURIComponent(roomId)}`;
            
            log(`尝试连接到: ${url}`);
            updateStatus('连接中...', 'connecting');
            
            ws = new WebSocket(url);
            
            ws.onopen = function(event) {
                log('✅ WebSocket连接已建立');
                updateStatus('已连接', 'connected');
                isConnected = true;
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('disconnectBtn').disabled = false;
            };
            
            ws.onmessage = function(event) {
                log(`📥 收到原始数据: ${event.data}`);
                
                try {
                    // 尝试解析为JSON
                    const message = JSON.parse(event.data);
                    log(`📥 解析成功: ${JSON.stringify(message, null, 2)}`);
                    
                    // 检查消息类型
                    switch(message.type) {
                        case 15:
                            log('🎉 收到好友状态列表消息!');
                            break;
                        case 11:
                            log('🏠 收到房间列表更新消息!');
                            break;
                        case 1:
                            log('👤 收到用户加入消息!');
                            break;
                        case 3:
                            log('💬 收到文本消息!');
                            break;
                        default:
                            log(`📋 收到类型 ${message.type} 的消息`);
                    }
                } catch (error) {
                    log(`❌ JSON解析失败: ${error.message}`);
                    log(`📄 原始数据长度: ${event.data.length}`);
                    log(`📄 原始数据前100字符: ${event.data.substring(0, 100)}`);
                }
            };
            
            ws.onclose = function(event) {
                log(`🔌 WebSocket连接已关闭: ${event.code} - ${event.reason}`);
                updateStatus('已断开', 'disconnected');
                isConnected = false;
                document.getElementById('connectBtn').disabled = false;
                document.getElementById('disconnectBtn').disabled = true;
            };
            
            ws.onerror = function(error) {
                log(`❌ WebSocket错误: ${error.message || '未知错误'}`);
                updateStatus('连接错误', 'disconnected');
            };
        }

        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }

        function sendMessage() {
            if (!isConnected || !ws) {
                alert('请先连接WebSocket');
                return;
            }
            
            const content = document.getElementById('messageInput').value;
            if (!content) {
                alert('请输入消息内容');
                return;
            }
            
            const message = {
                type: 3, // TEXT消息
                content: content,
                time: Date.now()
            };
            
            const messageStr = JSON.stringify(message);
            log(`📤 发送消息: ${messageStr}`);
            ws.send(messageStr);
            document.getElementById('messageInput').value = '';
        }

        function clearLog() {
            document.getElementById('log').textContent = '';
        }

        // HTTP API测试函数
        async function testOnlineCount() {
            try {
                log('🔍 测试在线用户数API...');
                const response = await fetch('http://localhost:8081/online/count', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    mode: 'cors'
                });
                const data = await response.json();
                log(`✅ 在线用户数: ${JSON.stringify(data, null, 2)}`);
            } catch (error) {
                log(`❌ 获取在线用户数失败: ${error.message}`);
            }
        }

        async function testUserStatus() {
            try {
                const userId = document.getElementById('userId').value;
                log(`🔍 测试用户状态API (用户ID: ${userId})...`);
                const response = await fetch(`http://localhost:8081/online/user?user_id=${userId}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    mode: 'cors'
                });
                const data = await response.json();
                log(`✅ 用户状态: ${JSON.stringify(data, null, 2)}`);
            } catch (error) {
                log(`❌ 获取用户状态失败: ${error.message}`);
            }
        }

        async function testFriendsStatus() {
            try {
                const userId = document.getElementById('userId').value;
                log(`🔍 测试好友状态API (用户ID: ${userId})...`);
                const response = await fetch(`http://localhost:8081/online/friends?user_id=${userId}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    mode: 'cors'
                });
                const data = await response.json();
                log(`✅ 好友状态: ${JSON.stringify(data, null, 2)}`);
            } catch (error) {
                log(`❌ 获取好友状态失败: ${error.message}`);
            }
        }

        async function testAllOnlineUsers() {
            try {
                log('🔍 测试所有在线用户API...');
                const response = await fetch('http://localhost:8081/online/users', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    mode: 'cors'
                });
                const data = await response.json();
                log(`✅ 所有在线用户: ${JSON.stringify(data, null, 2)}`);
            } catch (error) {
                log(`❌ 获取所有在线用户失败: ${error.message}`);
            }
        }

        // 页面加载时初始化
        window.onload = function() {
            log('页面已加载,可以开始测试');
        };
    </script>
</body>
</html> 